package vn.com.aptech.msh.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.model.UploadedFile;
import vn.com.aptech.msh.entities.User;

/**
 *
 * @author trietto
 */
public class FileUploadHelper {

    private static final int BUFFER_SIZE = 6124;


    public static void saveFile(UploadedFile uf, String filePath) throws FileNotFoundException, IOException {
        String fullPath = filePath + uf.getFileName();
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        FileOutputStream fileOutputStream = new FileOutputStream(fullPath);
        byte[] buffer = new byte[BUFFER_SIZE];
        int bulk;
        InputStream inputStream = uf.getInputstream();
        while (true) {
            bulk = inputStream.read(buffer);
            if (bulk < 0) {
                break;
            }
            fileOutputStream.write(buffer, 0, bulk);
            fileOutputStream.flush();
        }
        fileOutputStream.close();
        inputStream.close();
    }

    public static String getImagePath(User user) {
        String dir = "_";
        if (user != null) {
            dir = user.getUserID().toString();
        }
        return "images_upload/" + dir + "/";
    }

    public static String getSaveImagePath(FacesContext context, User user) {
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        String dir = "_";
        if (user != null) {
            dir = user.getUserID().toString();
        }
        String path = request.getServletContext().getRealPath("images_upload") + "/" + dir + "/";
        return path;
    }
}
